package com.wzk.travelspringboot.controller;

import com.wzk.travelspringboot.dto.PageQuery;
import com.wzk.travelspringboot.dto.Result;
import com.wzk.travelspringboot.dto.ScenicDTO;
import com.wzk.travelspringboot.dto.ViewDTO;
import com.wzk.travelspringboot.service.ScenicService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: WangZiKang
 * @Date: 2025/1/8 21:42
 */
@Slf4j
@RestController
@RequestMapping("/scenic")
@RequiredArgsConstructor
@Validated
public class ScenicController {

    private final ScenicService scenicService;

    @PostMapping("/add")
    public Result add( @RequestBody ScenicDTO dto){
        return scenicService.insert(dto);
    }


    @GetMapping("/all/page")
    public Result queryAll(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String area
    ){
        try {
            // 创建分页查询对象
            PageQuery pageQuery = new PageQuery();
            pageQuery.setPageNum(pageNum);
            pageQuery.setPageSize(pageSize);
            
            // 创建过滤条件Map
            Map<String, Object> filter = new HashMap<>();
            
            // 仅当type不为空时才添加到过滤条件
            if (type != null && !type.isEmpty()) {
                filter.put("type", type);
            }
            
            // 仅当area不为空时才添加到过滤条件
            if (area != null && !area.isEmpty()) {
                filter.put("area", area);
            }
            
            // 只有当过滤条件不为空时才设置到pageQuery
            if (!filter.isEmpty()) {
                pageQuery.setFilter(filter);
            }
            
            // 调用服务层方法
            return scenicService.queryAll(pageQuery);
        } catch (Exception e) {
            log.error("查询景区列表时发生错误: ", e);
            return Result.failed("查询景区列表失败: " + e.getMessage());
        }
    }


    @GetMapping("/{id}")
    public Result queryById(@PathVariable(name = "id") @NotBlank(message = "id不能为空") String id){
        return scenicService.queryById(Long.valueOf(id));
    }


    @GetMapping("/like/name")
    public Result queryLikeName(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize,
            @RequestParam(name = "name",required = true) @NotBlank String name
    ){
        return scenicService.queryLikeName(pageNum,pageSize,name);
    }

    @PostMapping("/view")
    public void view(@RequestBody ViewDTO dto){
        scenicService.view(dto);
    }

    @GetMapping("/all")
    public Result getAll(){
        return scenicService.all();
    }

}
